﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Zeus.Comunicaciones.Entidades
{
    public class ServiceResponse<T>
    {
        public string Message { get; set; }
        public bool Success { get; set; }
        public T Data { get; set; }
        public int CodeMessage { get; set; }

        public static ServiceResponse<T> From(Exception exception)
        {
            int codeMessage = 0;

            object[] attributes = exception.GetType().GetCustomAttributes(false);

            if (attributes != null)
            {
                NumberAttribute number = (NumberAttribute)attributes.SingleOrDefault(t => t.GetType() == typeof(NumberAttribute));

                if (number != default(NumberAttribute))
                {
                    codeMessage = number.Number;
                }
            }

            ServiceResponse<T> response = new ServiceResponse<T>
            {
                CodeMessage = codeMessage,
                Message = exception.Message,
                Success = false
            };

            return response;

        }

        public TDeribable Convert<TDeribable>() where TDeribable : class
        {
            dynamic entity = Activator.CreateInstance<TDeribable>();

            entity.Message = this.Message;
            entity.Success = this.Success;
            entity.Data = this.Data;
            entity.CodeMessage = this.CodeMessage;

            return entity;
        }
    }
}
